<?php

namespace App\Http\Controllers;

use App\Models\Transportation;
use App\Repositories\Transportation\TransportationFilter;
use App\Repositories\Transportation\TransportationRepository;
use App\Transformers\TransportationTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

use Maatwebsite\Excel\Facades\Excel;

class TransportationController extends Controller
{
    public function index(TransportationRepository $transportationRepository, Request $request)
    {
        $paginator = $transportationRepository->getPaginator(new TransportationFilter($request));
        return $this->response->paginator($paginator, new TransportationTransformer());
    }

    public function show($id)
    {
        $obj = Transportation::find($id)->with('users')->get();

        return $this->response->item($obj, new TransportationTransformer());
    }


    public function update($id)
    {

        return $this->response()->created('222', User::find($id));
    }


//    public function import(){
//        $filePath = 'storage/exports/员工信息表.xls';
//        Excel::load($filePath, function($reader) {
//            $reader = $reader->getSheet(0);
//            $results = $reader->toArray();
//            unset($results[0]);
//            dd($results);
//        });
//    }

    public function import(Request $request){
        if(!$request->hasFile('file')){
            exit('上传文件为空！');
        }
        $file = $_FILES;
        $excel_file_path = $file['file']['tmp_name'];

        $resume = [];
        Excel::load($excel_file_path, function($reader) use( &$resume ) {
            $reader = $reader->getSheet(0);
            $resume = $reader->toArray();
        });

        for($i = 1;$i<count($resume);$i++){
            $check = Transportation::where('id',$resume[$i][0])->where('riding_time',$resume[$i][4])->count();
            if($check){
                continue;
            }
            $elegance = new Transportation;
            $elegance->id = $resume[$i][0];
            $elegance->user_id = $resume[$i][1];
            $elegance->order_no = $resume[$i][2];
            $elegance->name = $resume[$i][3];
            $elegance->mobile = $resume[$i][4];
            $elegance->riding_time = $resume[$i][5];
            $elegance->origin = $resume[$i][6];
            $elegance->destination = $resume[$i][7];
            $elegance->total_price = $resume[$i][8];
            $elegance->distance = $resume[$i][9];
            $elegance->duration = $resume[$i][10];
            $elegance->note = $resume[$i][11];
            $elegance->additional = $resume[$i][12];
            $elegance->city = $resume[$i][13];
            $elegance->save();
        }
        return Redirect::to('/storage/exports')->withSuccess("导入成功");

    }


}


